<?php

namespace App\Http\Controllers\User;

use App\Services\GameRechargeService;
use App\Services\RechargeService;
use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class GamesController extends Controller
{


    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //查询用户游戏数据
        $userGameData = DB::table('game_data')
            ->select('id', 'type', 'server_name', 'server_ip', 'open_time', 'network', 'introduction', 'qq', 'url', 'count', 'audit', 'consume', 'publisher', 'release_date')
            ->where('publisher', Auth::user()->username)
            ->where(function ($query) {
                $query->orWhere('server_name', 'like', '%' . @$_GET['search'] . '%');
                $query->orWhere('server_ip', 'like', '%' . @$_GET['search'] . '%');
                $query->orWhere('open_time', 'like', '%' . @$_GET['search'] . '%');
                $query->orWhere('network', 'like', '%' . @$_GET['search'] . '%');
                $query->orWhere('introduction', 'like', '%' . @$_GET['search'] . '%');
                $query->orWhere('qq', 'like', '%' . @$_GET['search'] . '%');
                $query->orWhere('consume', 'like', '%' . @$_GET['search'] . '%');
                $query->orWhere('release_date', 'like', '%' . @$_GET['search'] . '%');
            })
            ->orderBy('id', 'desc')
            ->paginate(17)
            ->withPath('?search=' . @$_GET['search'] . '');

        return view('user.games.index', ['userGameData' => $userGameData]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //查询广告价格
        $price = DB::table('ad_price')
            ->select('id', 'yellow', 'all_day_yellow', 'overnight', 'fixed_overnight', 'all_day_boutique')
            ->get();

        return view('user.games.create', ['price' => $price]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        //验证表单
        $this->validate($request, [
            'type' => ['required','string','max:30'],
            'server_name' => ['required','string','max:8'],
            'server_ip' => ['required','string','max:8'],
            'open_time' => ['required','date','max:20'],
            'network' => ['required','string','max:7'],
            'introduction' => ['required','string','max:20'],
            'qq' => ['required','string','max:15'],
            'count' => ['required','numeric','max:100'],
            'url' => ['required','string','max:50'],
        ]);

        //字符串分割
        $type = explode(",", $request->type);
        //查询广告价格
        $AdPrice = DB::table('ad_price')->select('id', 'yellow', 'all_day_yellow', 'overnight', 'fixed_overnight', 'all_day_boutique')->get();

        $yellow = $type[0] == '1' ? $AdPrice[0]->yellow : '0';
        $allDayYellow = $type[1] == '1' ? $AdPrice[0]->all_day_yellow : '0';
        $overnight = $type[2] == '1' ? $AdPrice[0]->overnight : '0';
        $fixedOvernight = $type[3] == '1' ? $AdPrice[0]->fixed_overnight : '0';
        $allDayBoutique = $type[4] == '1' ? $AdPrice[0]->all_day_boutique : '0';
        //价格总和
        $totalPrice = ($yellow + $allDayYellow + $overnight + $fixedOvernight + $allDayBoutique) * $request->count;

        //检测账户余额
        if ($totalPrice > Auth::user()->money) {
            return response()->json(['message' => 'The given data was invalid.', 'errors' => ['money' => ['账户余额不足。']]], 200);
        } else {
            //扣除账户金额
            DB::table('users')->where('id', Auth::id())->decrement('money', $totalPrice);

            //写入添加的游戏
            DB::table('game_data')->insert([
                'type' => $request->type,
                'server_name' => $request->server_name,
                'server_ip' => $request->server_ip,
                'open_time' => $request->open_time,
                'network' => $request->network,
                'introduction' => $request->introduction,
                'qq' => $request->qq,
                'url' => $request->url,
                'count' => $request->count,
                'audit' => 1,
                'consume' => $totalPrice,
                'publisher' => Auth::user()->username,
                'release_date' => date('Y-m-d H:i:s')
            ]);

            return response()->json(['message' => '发布成功。', 'success' => 'true']);

        }
    }

    /**
     * 显示抽奖页面
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showDrawPage(Request $request)
    {
        return view('user.draw_page', ['gameId' => $request->get('game_id', 0)]);
    }

    /**
     * 抽奖
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public function draw(Request $request)
    {
        $gameId = $request->post('game_id', 0);
        if (!$gameId) {
            return errorResp('game_id empty');
        }
        $game = DB::table('game_data')->find($gameId);
        if (!$game) {
            return errorResp('game error');
        }
        // 判断时间
        $nowHour = (int)date('H');
//        if ($nowHour < 8) {
//            return response()->json(['message' => '当前系统已关闭，08:00-24:00为开放状态', 'success' => 'false'], 200);
//        }
        $uid = $this->getUid();
        // 事务控制
        DB::beginTransaction();
        try {
            // 一天只能抽奖一次，update锁
            $isDraw = DB::table('draw_log')
                ->lockForUpdate()
                ->where('user_id', $uid)
                ->where('draw_id', '>',0)
                ->where('create_time', '>=', date("Y-m-d") . " 00:00:00")
                ->count();
            if ($isDraw) {
                throw new \Exception('大侠今日已经抽奖，请明日再来');
            }
            // 产生奖品
            $draws = DB::table('draw')->get();
            $box = [];
            $drawInfo = [];
            foreach ($draws as $draw) {
                for ($i=0; $i<$draw->rate; $i++) {
                    $box[] = $draw->id;
                }
                $drawInfo[$draw->id] = $draw;
            }
            $drawId = $box[array_rand($box)];
            $sourceUrl  = $_SERVER['HTTP_HOST'];
            // 写入中奖信息
            $id = DB::table('draw_log')->insertGetId([
                'user_id' => $uid,
                'draw_id' => $drawId,
                'is_luck' => $drawInfo[$drawId]->is_luck,
                'money' =>   (int)ceil(($drawInfo[$drawId]->money / 100)),  //因兑换脚本要换成人民币点 所以这里 除100  向上取整
                'create_time' => date('Y-m-d H:i:s'),
                'status' => 2,
                'source_url' => $sourceUrl,
                'game_id' => $gameId,
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => $e->getMessage(), 'success' => 'false'], 200);
        }
        DB::commit();
        if ($drawInfo[$drawId]->is_luck == 1) {
            $msg = '恭喜您，获得'. $drawInfo[$drawId]->title . '充值到账时会通过公众号通知您，请留意公众号！';
        } else {
            $msg = '很遗憾，就差一点点了，请明日再来';
        }
        return response()->json(['message' => $msg, 'success' => 'true', 'data' => [
            'anger' => $drawInfo[$drawId]->anger,
            'id' => $id,
            'is_luck' => $drawInfo[$drawId]->is_luck
        ]], 200);
    }

    /**
     * 提交领奖信息
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function commitDrawNum()
    {
        $nowHour = (int)date('H');
//        if ($nowHour < 8) {
//            return response()->json(['message' => '当前系统已关闭，08:00-24:00为开放状态', 'success' => 'false'], 200);
//        }
        $request = request();
        $id = $request->post('id');
        $game_num = $request->post('game_num');
        $re_game_num = $request->post('re_game_num');
        $game_server = $request->post('game_server');
        $date = $request->post('date','今日');
        if (!$id) {
            return response()->json(['message' => '信息错误', 'success' => 'false'], 200);
        }
        if (!$game_num) {
            return response()->json(['message' => '请输入领奖游戏账号', 'success' => 'false'], 200);
        }
        if ($game_num != $re_game_num) {
            return response()->json(['message' => '两次输入的领奖游戏账号不一致', 'success' => 'false'], 200);
        }
        if (!$game_server) {
            return response()->json(['message' => '你没有选择区服', 'success' => 'false'], 200);
        }

        $uid = $this->getUid();
        $log = DB::table('draw_log')->find($id);
        if (!$log) {
            return response()->json(['message' => '信息错误', 'success' => 'false'], 200);
        }
        if ($log->user_id != $uid) {
            return response()->json(['message' => '提交非法', 'success' => 'false'], 200);
        }
        if ($log->is_luck != 1) {
            return response()->json(['message' => '没有中奖，无需填写信息', 'success' => 'false'], 200);
        }
        if ($log->status == 1) {
            return response()->json(['message' => '您的中奖记录已处理完毕，请注意查收', 'success' => 'false'], 200);
        }
        $game_id = $log->game_id;
        if (!$game_id) {
            return response()->json(['message' => '游戏信息错误', 'success' => 'false'], 200);
        }
        $game = DB::table('game_data')->find($game_id);
        if (empty($game)) {
            return response()->json(['message' => '游戏选择错误', 'success' => 'false'], 200);
        }
        $game_url = $game->server_name;
        if ($log->draw_id == -1) {
            // 每个用户一天一次
            $userTodayCount = DB::table('draw_log')
                ->where('user_id', $uid)
                ->where('draw_id', '=', -1)
                ->where('create_time', '>', date('Y-m-d 00:00:00'))
                ->count();
            if ($userTodayCount) {
                return response()->json(['message' => '今日已领取，请明日再来', 'success' => 'false'], 200);
            }
            if ($game->count > 0) {
                // 领取的检查游戏可领取数量
                $todayGetNum = DB::table('draw_log')
                    ->where('game_id', $game->id)
                    ->where('draw_id', '=', -1)
                    ->where('create_time', '>', date('Y-m-d 00:00:00'))
                    ->count();
                if ($todayGetNum >= $game->count) {
                    return response()->json(['message' => '游戏今日福利发放完毕', 'success' => 'false'], 200);
                }
            }

            //红包一个账号一天只能一次
            $hbhas = DB::table('draw_log')
                ->where('game_num', $game_num)
                ->where('game_url', $game_url)
                ->where('draw_id', '>', -1)
                ->where('create_time', '>', date('Y-m-d 00:00:00'))
                ->first();

            if ($hbhas) {
                return response()->json(['message' => '该账号今日已领取福利，请明日再来', 'success' => 'false'], 200);
            }
        }else{//抽奖
            // 每个用户一天一次
            $userTodayCount = DB::table('draw_log')
                ->where('user_id', $uid)
                ->where('draw_id', '>',0 )
                ->where('create_time', '>', date('Y-m-d 00:00:00'))
                ->where('game_num', '!=', "")
                ->count();
            // var_dump($uid);die;
            if ($userTodayCount) {
                return response()->json(['message' => '今日已领取，请明日再来', 'success' => 'false'], 200);
            }
        }



        // 判断当前账号今天是否已经提交
        $has = DB::table('draw_log')
            ->where('game_num', $game_num)
            ->where('game_url', $game_url)
            ->where('draw_id', '>', 0)
            ->where('create_time', '>', date('Y-m-d 00:00:00'))
            ->first();

        if ($has) {
            return response()->json(['message' => '该账号今日已领取福利，请明日再来', 'success' => 'false'], 200);
        }



        // 查询游戏信息
        $updateArray = [
            'game_num' => $game_num,
            'game_url' => $game_url,
            'game_server' => $game_server,
            'status' => 2,
            'msg' => '',
            'date' => $date,
            'game_id' => $game->id,
        ];
        if ($game->is_tq == 1 ) {
            $isGet = DB::table('draw_log')
                ->where('game_url', $game->server_name)
                ->where('game_num', $request->game_num)
                ->where('draw_id', '>', 0)
                ->count();
            if ($isGet) {
                return response()->json(['message' => '该账号已经领取奖励，请勿重复领取', 'success' => 'false']);
            }
            $updateArray['draw_id'] = 14;
        }



        DB::table('draw_log')->where('id', $id)->update($updateArray);
        return response()->json(['message' => '领取成功，充值到账时会通过公众号通知您，请留意公众号！', 'success' => 'true'], 200);
    }

    /**
     * 获取当前登录的用户信息
     * @return mixed
     */
    public function getUid()
    {
        return request()->userInfo->id;
    }

    /**
     * 获取今日抽奖情况
     * @return \Illuminate\Http\JsonResponse
     */
    public function todayDraw()
    {
        // echo  111;die;
        $uid = $this->getUid();
        // 一天只能抽奖一次
        $isDraw = DB::table('draw_log')
            ->where('user_id', $uid)
            ->where('draw_id', '>', 0)
            ->where('create_time', '>=', date("Y-m-d") . " 00:00:00")
            ->first();
        if ($isDraw) {
            return response()->json(['message' => '', 'success' => 'true', 'data' => $isDraw], 200);
        }
        return response()->json(['message' => '', 'success' => 'true', 'data' => false], 200);
    }


    /**
     * 获取游戏的充值数据
     * {
    "game_num": "我是游戏账号",
    "version_name": "我是版本名称",
    "area": "我是区",
    "unionid": "我是unionid",
    "mechanical_code": "我是机械码",
    "amount": 30,
    "record_time": "2023-03-22 10:51:08"
    }
     * @return \Illuminate\Http\JsonResponse
     */
    public function gameRecharges()
    {
        $data =    json_decode(htmlspecialchars_decode(file_get_contents("php://input")),true);
        DB::beginTransaction();
        try {
            $addArray = [];
            if ($data["type"] ==1) {
                foreach ($data['data'] as $key => $value){
                    if ($value['amount'] >0) {
                        $value["create_time"] = date("Y-m-d H:i:s");
                        $addArray[] = $value;
                    }
                }
            }

            // 插入获取数据
            $res = DB::table('game_recharge')->insert($addArray);
            if (!$res) {
                throw new \Exception('写入失败');
            }
            DB::commit();
            return response()->json(['code'=>1,'message' => '成功。', 'success' => 'true']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code'=>11,'message' => "失败", 'success' => 'false']);
        }
    }

    /**
     * 游戏充值页面
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function recharge($param)
    {
        if (!$param) {
            return '参数错误';
        }
        $unionId = '';
        $gameVersion = '';
        $gameServer = '';
        $gameAccount = '';
        $gameRole = '';
        $platName = '';
        $items = explode('&', $param);
        foreach ($items as $v) {
            $kv = explode(':', $v);
            if (count($kv) != 2) {
                return '参数错误';
            }
            if ($kv[0] == 'union_id') { $unionId = $kv[1]; }
            if ($kv[0] == 'game_server') { $gameServer = $kv[1]; }
            if ($kv[0] == 'game_account') { $gameAccount = $kv[1]; }
            if ($kv[0] == 'game_version') { $gameVersion = $kv[1]; }
            if ($kv[0] == 'game_role') { $gameRole = $kv[1]; }
            if ($kv[0] == 'plat_name') { $platName = $kv[1]; }
        }

        if (!$unionId || !$gameVersion || !$gameServer) {
            return '用户信息错误';
        }
        $userInfo = DB::table('users')->where('unionid', $unionId)->first();
        if (!$userInfo) {
            return '用户信息错误';
        }
        $orderNo = date('YmdHis').$userInfo->id.'3'.mt_rand(100, 999);
        return view('user.game_recharge', compact('orderNo', 'unionId', 'gameServer', 'gameVersion', 'gameAccount', 'gameRole', 'platName'));
    }

    /**
     * 充值支付
     */
    public function rechargePay(Request $request)
    {
        //验证表单
        $this->validate($request, [
            'union_id' => ['required','string'],
            'game_server' => ['required','string'],
            'game_account' => ['required','string'],
            'game_version' => ['required','string'],
            'game_role' => ['required','string'],
            'money' => ['required','int'],
            'pay_type' => ['required','string'],
            'order_no' => ['required','string'],
            'plat_name' => ['required','string']
        ]);
        $userInfo = DB::table('users')->where('unionid', $request->union_id)->first();
        if (!$userInfo) {
            return errorResp('用户信息错误');
        }
        $gameInfo = [
            'game_version' => $request->game_version,
            'game_account' => $request->game_account,
            'game_server' => $request->game_server,
            'game_role' => $request->game_role,
            'qq' => $request->qq,
        ];
        $res = GameRechargeService::startPay($userInfo->id, $request->money, $request->pay_type, $gameInfo, $request->order_no, $request->plat_name);
        return successResp($res);
    }
}

